package com.project.nimsen.web.sys;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.project.nimsen.constant.NimsenConstant;
import com.project.nimsen.dto.ArchivesDto;
import com.project.nimsen.dto.ColumnDto;
import com.project.nimsen.dto.FileInfoDto;
import com.project.nimsen.dto.UrlinfoDto;
import com.project.nimsen.entity.Archives;
import com.project.nimsen.service.IArchivesService;
import com.project.nimsen.service.IColtypeService;
import com.project.nimsen.service.IFileinfoService;
import com.project.nimsen.service.IUrlinfoService;
import com.project.nimsen.util.WebUtil;
import com.project.jdbc.utils.DateUtils;
import com.project.jdbc.utils.Page;
import com.project.jdbc.web.BaseMVCAction;
/**
 * 文章Control
 * */
@Controller
@RequestMapping(value ="/sys/archives")
public class ArchivesControl extends BaseMVCAction {
	@Resource
	WebUtil webUtil;
	@Resource
	IArchivesService archService;
	@Resource
	IColtypeService coltypeService;
	@Resource
	IFileinfoService fileinfoService;
	@Resource
	IUrlinfoService urlinfoService;
	/**
	 * ajax验证是否重复
	 * */
	@RequestMapping(value = "/validate")
	public void validate(HttpServletRequest request,HttpServletResponse response){
		//返回JSON信息
		JSONObject map = new JSONObject();
		//查询条件设置
		ArchivesDto dto = new ArchivesDto();
		dto.setValtitle(getParameter("title"));
		dto.setValid(getParameter("id"));
		try {
			List<Map<String, Object>> rows = archService.finder(dto);
			if(CollectionUtils.isEmpty(rows))
				map.put("success", true);
			else
				map.put("success", false);
			response.getWriter().println(map.toString());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
	}
	/**
	 * 查询方法
	 * */
	@RequestMapping(value = "/search")
	@ResponseBody
	public Map<String, Object> search(HttpServletRequest request,HttpServletResponse response){
		//分页信息
		Page page = new Page(getIntegerParameter("page"));
		page.setPageSize(getIntegerParameter("rows"));
		//返回JSON信息
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("total", 0);
		//查询条件设置
		ArchivesDto dto = new ArchivesDto();
		dto.setPage(page);
		dto.setFinderType("zhu");
		//查询信息
		try {
			dto.setCreateuser(webUtil.currSite(request).getManagerid());
			List<Map<String, Object>> rows = archService.finder(dto);
			if(CollectionUtils.isEmpty(rows)){
				map.put("rows", "");
				return map;
			}
			//转换时间
			for(Map<String, Object> row : rows){
				Date createTime = (Date)row.get("createTime");
				row.put("createTime", DateUtils.convertDate2String(createTime));
			}
			map.put("rows", rows);
			map.put("total", page.getTotalCount());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return map;
	}
	@RequestMapping(value ="/list")
	public String list(){
		return "/WEB-INF/sys/archives/list";
	}
	/**
	 * 添加一个文章的方法
	 * */
	@RequestMapping(value ="/add")
	public void add(HttpServletRequest request,HttpServletResponse response){
//		key:summary--------value:safwe
//		key:zhucolname--------value:技术资料
//		key:textcontent--------value:asd
//		key:microimgid--------value:216271cb-ef05-486b-9524-4d056ef364da
//		key:tag--------value:ew,sadf
//		key:fucolname--------value:我的产品,我的产品展示
//		key:author--------value:saa
//		key:title--------value:asdf
//		key:shottitle--------value:ss
//		key:sourceurl--------value:asdfv
//		key:fucolnameid--------value:004,005
//		key:htmlcontent--------value:<span style="color:#ff9900;">asd</span>
//		key:zhucolnameid--------value:003
		String currUserId = webUtil.getCurrUser().getId();
		ArchivesDto dto = new ArchivesDto();
		//文章的一些辅助信息
		dto.setFucolname(getParameter("fucolname"));
		dto.setFucolnameid(getParameter("fucolnameid"));
		dto.setMicroimgid(getParameter("microimgid"));
		dto.setZhucolname(getParameter("zhucolname"));
		dto.setZhucolnameid(getParameter("zhucolnameid"));
		dto.setCurrUserId(currUserId);
		dto.setImglist(getParameter("imglist"));
		dto.setUrlist(getParameter("urlist"));
		
		String id = getParameter("id");
		Archives arch = null;
		try {
			//处理实体类的属性
			if(StringUtils.isNotBlank(id)){
				arch = archService.findEntityById(id);
				arch.setUpdateTime(new Date());
			}else{
				arch = new Archives();
				arch.setActive(0);
				arch.setCreateTime(new Date());
				arch.setCreateUser(currUserId);
				arch.setUpdateTime(new Date());
				arch.setTitle(getParameter("title"));
				arch.setShottitle(getParameter("shottitle"));
			}
			arch.setAuthor(getParameter("author"));
			String htmlcontent = getParameter("htmlcontent");
			//替换所有的图片路径
			if(StringUtils.isNotBlank(htmlcontent)){
				//htmlcontent = htmlcontent.replaceAll("/pub/file/", WebUtil.webUrl(request)+"/pub/file/");
			}
			arch.setHtmlcontent(htmlcontent);
			arch.setSourceurl(getParameter("sourceurl"));
			arch.setSummary(getParameter("summary"));
			arch.setTag(getParameter("tag"));
			String textcontent = getParameter("textcontent");
			//替换所有的图片路径
			if(StringUtils.isNotBlank(textcontent)){
				//textcontent = textcontent.replaceAll("/pub/file/", WebUtil.webUrl(request)+"/pub/file/");
			}
			arch.setTextcontent(textcontent);
			
			dto.setArch(arch);
			
			//返回JSON信息
			JSONObject map = new JSONObject();
			map.put("success", false);//保存失败
			archService.save(dto);
			map.put("success", true);//保存成功
			response.getWriter().println(map.toString());
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
	}
	/**
	 * 向前台返回一个实体
	 * */
	@RequestMapping(value = "/bean")
	@ResponseBody
	public Map<String, Object> bean(HttpServletRequest request){
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			String archid = getParameter("id");
			//文档实体类本身的信息
			Map<String, Object> entity = archService.findById(archid);
			if(entity==null){
				map.put("success", false);
				map.put("message", " 找不到要操作的文章！");
				return map;
			}
			//得到关联的栏目
			ColumnDto colDto = new ColumnDto();
			colDto.setArchid(archid);
			List<Map<String, Object>> cols = coltypeService.findByArchInfo(colDto);
			if(CollectionUtils.isEmpty(cols)){
				map.put("success", false);
				map.put("message", " 找不到要操作文章的所属栏目！");
				return map;
			}
			StringBuffer fucolname = new StringBuffer();
			StringBuffer fucolid = new StringBuffer();
			//处理栏目信息
			for(Map<String, Object> col : cols){
				String mancol = col.get("mancol").toString();
				String colname = col.get("colname").toString();
				String colid = col.get("number").toString();
				if("0".equals(mancol)){
					entity.put("zhucolumnname", colname);
					entity.put("zhucolumnid", colid);
					continue;
				}
				fucolname.append(colname).append(",");
				fucolid.append(colid).append(",");
			}
			String funame = fucolname.toString();
			String fuid = fucolid.toString();
			//处理组成字符串后的","号
			if(StringUtils.isNotBlank(funame)){
				entity.put("fucolumnname", funame.substring(0, funame.lastIndexOf(",")));
				entity.put("fucolumnid", fuid.substring(0, fuid.lastIndexOf(",")));
			}else{
				entity.put("fucolumnname", "");
				entity.put("fucolumnid", "");
			}
			//处理缩略图信息
			FileInfoDto fdto = new FileInfoDto();
			fdto.setArchid(archid);
			fdto.setRelatiovalue(NimsenConstant.FILE_RELATION_MICROIMG);
			List<Map<String, Object>> imgs = fileinfoService.findFileInfoByDto(fdto);
			if(!CollectionUtils.isEmpty(imgs)){
				//处理缩略图信息
				for(Map<String, Object> img : imgs){
					entity.put("imgid", img.get("id"));
					entity.put("imgsrc", img.get("filename"));
				}
			}
			
			//处理图片集合信息
			fdto.setRelatiovalue(NimsenConstant.FILE_RELATION_IMGLIST);
			List<Map<String, Object>> imglist = fileinfoService.findImgListByDto(fdto);
			if(!CollectionUtils.isEmpty(imglist)){
				//处理图片集合
				StringBuffer imgliststr = new StringBuffer();
				for(Map<String, Object> img : imglist){
					imgliststr.append(img.get("fileid")).append("※");
					imgliststr.append(img.get("descs")).append("※");
					imgliststr.append(img.get("filename")).append("§");
				}
				//处理最后一个字符
				String listimgstr = imgliststr.toString();
				map.put("imglist", listimgstr.subSequence(0, listimgstr.length()-1));
			}
			
			//处理url集合
			UrlinfoDto udto = new UrlinfoDto();
			udto.setUrloutid(archid);
			udto.setUrloutable(NimsenConstant.ARCHIVES_URL_LIST);
			List<Map<String, Object>> urls = urlinfoService.findUrlListByDto(udto);
			//处理url链接
			if(!CollectionUtils.isEmpty(urls)){
				StringBuffer urlsliststr = new StringBuffer();
				for(Map<String, Object> url : urls){
					urlsliststr.append(url.get("url")).append("§");
				}
				//处理最后一个字符
				String listurlstr = urlsliststr.toString();
				map.put("urlist", listurlstr.subSequence(0, listurlstr.length()-1));
			}
			
			map.put("success", true);
			map.put("bean", entity);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
			map.put("success", false);
		}
		return map;
	}
	/**
	 * 删除一个权限
	 * */
	@RequestMapping(value = "/delete")
	@ResponseBody
	public Map<String, Object> delete(HttpServletRequest request){
		Map<String,Object> map = new HashMap<String,Object>();
		ArchivesDto dto = new ArchivesDto();
		String id = getParameter("id");
		dto.setId(id);
		try {
			//查询要删除的目录下是否还有文档信息
			archService.deleteByDto(dto);
			map.put("success", true);
		} catch (Exception e) {
			e.printStackTrace();
			logger.error(e);
		}
		return map;
	}
}
